//
//  LXHomeViewController.swift
//  weibo
//
//  Created by lixin on 16/4/16.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

class LXHomeViewController: LXVisitorTableViewController {
    
    let HomeTableViewCellIdentifierId = "cellIdentifierId"
    
    var status: [LXStatus] = [LXStatus]()//保存微博数据的数组

    override func viewDidLoad() {
        super.viewDidLoad()
    
        if !isLogin {
            
            visitorView?.setVisitorInfo(imgName: nil, title: nil)
            
            return
        }
        
        setUI()
        
        setTableViewInfo()
        
        loadData(indicatorView.isAnimating())
    }
    
    private func setTableViewInfo(){
    
        tableView.registerClass(LXStatusCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifierId)
        
        tableView.rowHeight = UITableViewAutomaticDimension //自动计算行高
        
        tableView.estimatedRowHeight = 200 //预估行高
        
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = indicatorView
        
        tableView.addSubview(refresh)
        
        refresh.addTarget(self, action: #selector(LXHomeViewController.refreshAction), forControlEvents: UIControlEvents.ValueChanged)
    }
    
    //MARK: - 监听刷新数据的方法
    @objc private func refreshAction(){
    
        loadData(indicatorView.isAnimating())
    }
    
    private func setUI(){
        navigationController!.view.insertSubview(showCountLabel, belowSubview: navigationController!.navigationBar)
        
        showCountLabel.frame = CGRect(x: 0, y: 64 - 34, width: SCREENW, height: 34)
    }
    
    // MARK: -  懒加载控件
    private lazy var indicatorView : UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        indicatorView.color = ThemeColor
      
        return indicatorView
    }()
    
    private lazy var refresh: LXRefreshControl = LXRefreshControl()
    
    private lazy var showCountLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.whiteColor(), textFont: 14)
        
        label.textAlignment = .Center
        
        label.backgroundColor = ThemeColor
        
        label.hidden = true
        
        return label
        
    }()
}

//MARK: - tableView的代理方法
extension LXHomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return status.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifierId, forIndexPath: indexPath) as! LXStatusCell
        
        cell.status = status[indexPath.row]
        
        return cell

    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
       
        if indexPath.row == status.count - 1 && !indicatorView.isAnimating(){
            
            indicatorView.startAnimating()
            
            loadData(indicatorView.isAnimating())
        }
    }
    
}

//MARK: - 请求首页数据（加入了上拉加载更多/下拉刷新）
extension LXHomeViewController{

    func loadData(isPullUp: Bool){
    
        var sinceId: Int64 = 0
        
        var maxId: Int64 = 0
        
        if isPullUp{
        
            sinceId = 0
            
            maxId = status.last!.id ?? 0
            
            if maxId > 0 {
                
                maxId = maxId - 1
            }
        
        }else{
        
            sinceId = status.first?.id ?? 0
            
            maxId = 0
        }
        
        LXStatusDAL.getHomeStatus(sinceId, max_id: maxId) { (array) in
            
            self.endRefreshing()
            
            if array.count == 0{
            
                print("获取数据失败")
                
                return
            }
            
            var tempArray:[LXStatus] = [LXStatus]()
            
            for dic in array{
                
                let status = LXStatus(dict: dic)
                
                tempArray.append(status)
            }
            
            // 上拉加载更多
            if isPullUp{
                
                self.status = self.status + tempArray
                
            }else{
                
                // 下拉刷新
                self.status = tempArray + self.status
                
                if self.showCountLabel.hidden == true{
                    
                    self.setShowCountLabelAnim(tempArray.count)
                }
            }
            
            // 刷新UI
            self.tableView.reloadData()
        }
    }
    
    func endRefreshing(){
        
        self.indicatorView.stopAnimating()
        
        self.refresh.endRefreshing()
    }
    
    func setShowCountLabelAnim(count: Int){
        
        showCountLabel.hidden = false
        
        var countString = ""
        
        if count == 0{
            
            countString = "暂无微博更新，请您休息一下再试"
            
        }else{
            
            countString = "更新了\(count)条微博"
        }
        
        showCountLabel.text = countString
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.showCountLabel.frame.origin.y = 64
            
        }) { (_) -> Void in
            
            UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                
                self.showCountLabel.frame.origin.y = 64 - 34
                
                }, completion: { (_) -> Void in
                    
                    self.showCountLabel.hidden = true
            })
        }
    }
    
}

